<template>
  <a-modal
    :visible="visible"
    title="创建油耗"
    :destroyOnClose="true"
    width="666px"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form-model
      ref="ruleForm"
      :model="form"
      :rules="rules"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
    >
      <a-row>
        <a-col :span="12">
          <a-form-model-item prop="businessType" label="业务类型">
            <a-select v-model="form.businessType">
              <a-select-option key>请选择</a-select-option>
              <a-select-option key="SHUNTING">业务调车</a-select-option>
              <a-select-option key="UPKEEP">车辆保养</a-select-option>
              <a-select-option key="REPAIR">车辆维修</a-select-option>
              <a-select-option key="ANNUAL">车辆年检</a-select-option>
              <a-select-option key="OTHER">其他</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="tractorId" label="牵引车车牌号">
            <a-select
              show-search
              :show-arrow="false"
              :filter-option="false"
              :default-active-first-option="false"
              :not-found-content="null"
              @search="handleCarNameChange"
              @select="handleCarSelect"
            >
              <a-select-option v-for="d in carLikeData" :key="d.tractorId">{{ d.tractorNumber }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="driverId" label="司机">
            <a-select
              show-search
              v-model="form.driverId"
              :show-arrow="false"
              :filter-option="false"
              :default-active-first-option="false"
              :not-found-content="null"
              @search="queryDriverDown"
              @select="emptyChange1"
            >
              <a-select-option
                v-for="d in driverLikeData"
                :key="d.driverId"
              >{{ d.name }} - {{d.phone}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="挂车车牌号">
            <a-select
              show-search
              v-model="form.trailerId"
              :show-arrow="false"
              :filter-option="false"
              :default-active-first-option="false"
              :not-found-content="null"
              @search="queryTruckNumberDown"
              @select="emptyChange2"
            >
              <a-select-option v-for="d in truckNumberLikeData" :key="d.truckId">{{ d.truckNumber }}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item label="备注" :labelCol="{span:5}" :wrapperCol="{span:18}">
            <a-textarea v-model="form.remark" :rows="3"></a-textarea>
          </a-form-model-item>
        </a-col>
        <a-col :span="24">
          <a-form-model-item
            prop="voucherPics"
            label="上传凭证"
            :labelCol="{span:5}"
            :wrapperCol="{span:18}"
          >
            <ud-upload @uploadFile="voucherPicsUpload"></ud-upload>
          </a-form-model-item>
        </a-col>

        <a-divider dashed />

        <a-col :span="12">
          <a-form-model-item prop="mileage" label="里程数(km)">
            <a-input-number
              :min="0"
              :max="999999999999.99"
              :precision="2"
              v-model="form.mileage"
              @change="onChangeK1"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="耗油系数(L/km)">
            <a-select v-model="rateKey" @change="onChangeK2">
              <a-select-option v-if="!currentSelectCar.singleOilConsumption" key>请先选择牵引车</a-select-option>
              <a-select-option
                v-if="currentSelectCar.singleOilConsumption || currentSelectCar.singleOilConsumption === 0"
                key="singleOilConsumption"
              >单重：{{currentSelectCar.singleOilConsumption}}</a-select-option>
              <a-select-option
                v-if="currentSelectCar.doubleOilConsumption || currentSelectCar.doubleOilConsumption === 0"
                key="doubleOilConsumption"
              >双重：{{currentSelectCar.doubleOilConsumption}}</a-select-option>
              <a-select-option
                v-if="currentSelectCar.emptyOilConsumption || currentSelectCar.emptyOilConsumption === 0"
                key="emptyOilConsumption"
              >空车：{{currentSelectCar.emptyOilConsumption}}</a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item prop="oilVolume" label="耗油量(L)">
            <a-input-number
              :min="0"
              :precision="2"
              v-model="form.oilVolume"
              @change="oilVolumeChange"
              style="width: 100%"
            />
          </a-form-model-item>
        </a-col>
        <a-col :span="12">
          <a-form-model-item label="油耗费用(元):">
            {{oilDetail.totalAmount}}
            <a
              style="margin-left: 20px"
              @click="() => {detailClose = !detailClose}"
            >{{detailClose?'收起':'显示'}}价格明细</a>
          </a-form-model-item>
        </a-col>
        <a-col :span="24" v-show="detailClose">
          <a-table
            size="small"
            :columns="columns"
            :data-source="oilDetail.purchaseList"
            :pagination="false"
            rowKey="batchNo"
          ></a-table>
        </a-col>
      </a-row>
    </a-form-model>
  </a-modal>
</template>

<script>
import { Divider } from 'ant-design-vue'
import debounce from 'lodash/debounce'
import upload from '@/components/UpLoad'
import { queryDriverDown } from '@/api'
import { queryTractorBindInfoDown, queryTruckNumberDown, queryTruckOilInByOilVolume, addTruckOilInAndOutByOut } from '@/api/landCenter'

const fomrMessage = `必填项不能为空`
const initData = () => {
  return {
    carLikeData: [],
    currentSelectCar: {
      trailerId: '', // 挂车id
      trailerNumber: '', // 挂车车牌
      singleOilConsumption: '', // 单重油耗
      doubleOilConsumption: '', // 双重油耗
      emptyOilConsumption: '' // 空车
    },
    rateKey: '',
    truckNumberLikeData: [],
    driverLikeData: [],
    form: {
      tractorId: '', // 牵引车id
      driverId: '', // 司机id
      trailerId: '', // 挂车id
      businessType: '',
      mileage: '', // 里程数
      rate: '', // 耗油系数
      oilVolume: '', // 油量
      voucherPics: ''// 加油凭证
    },
    // 明细
    detailClose: false,
    oilDetail: {
      totalAmount: '--',
      purchaseList: []
    }
  }
}

export default {
  name: 'create-other-business',
  props: ['visible'],
  data () {
    this.queryTruckNumberDown = debounce(this.queryTruckNumberDown, 800)
    this.queryDriverDown = debounce(this.queryDriverDown, 800)
    this.handleCarNameChange = debounce(this.handleCarNameChange, 800)
    this.oilVolumeChange = debounce(this.oilVolumeChange, 800)

    return {
      labelCol: { span: 10 },
      wrapperCol: { span: 12 },
      ...initData(),
      rules: {
        businessType: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        tractorId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        driverId: [{ required: true, message: fomrMessage, trigger: ['blur', 'change'] }],
        mileage: [{ required: true, message: fomrMessage, trigger: 'blur' }],
        oilVolume: [{ required: true, message: fomrMessage, trigger: 'blur' }]
        // voucherPics: [{required: true, message: fomrMessage}]
      },
      columns: [{
        title: '采购批次',
        dataIndex: 'batchNo'
      }, {
        title: '单价(元/L)',
        dataIndex: 'price'
      }, {
        title: '油量(L)',
        dataIndex: 'oilVolume'
      }, {
        title: '交易金额(元)',
        dataIndex: 'amount'
      }],
      confirmLoading: false
    }
  },
  components: {
    [Divider.name]: Divider,
    'ud-upload': upload
  },
  methods: {
    voucherPicsUpload (urls) {
      this.form.voucherPics = urls
    },
    handleCarNameChange (nameLike = '') { // 自营牵引车绑定信息
      queryTractorBindInfoDown({
        word: nameLike
      }).then(rsp => {
        this.carLikeData = rsp.data
      })
    },
    queryDriverDown (word = '') {
      queryDriverDown({ word, status: 1 }).then(rsp => {
        this.driverLikeData = rsp.data
      })
    },
    emptyChange1 () {
      this.queryDriverDown()
    },
    queryTruckNumberDown (truckNumber = '') {
      queryTruckNumberDown({ truckNumber, isSelfOperation: 1, status: 1 }).then(rsp => {
        this.truckNumberLikeData = rsp.data
      })
    },
    emptyChange2 () {
      this.queryTruckNumberDown()
    },
    onChangeK1 () {
      this.form.oilVolume = Math.round(this.form.mileage * this.form.rate * 100) / 100
      this.oilVolumeChange()
    },
    onChangeK2 () {
      this.form.rate = this.rateKey ? this.currentSelectCar[this.rateKey] : ''
      this.form.oilVolume = Math.round(this.form.mileage * this.form.rate * 100) / 100
      this.oilVolumeChange()
    },
    oilVolumeChange () {
      if (this.form.oilVolume) {
        this.form.mileage = Math.round(this.form.oilVolume / this.form.rate * 100) / 100
        if (this.currentSelectCar.tractorId && this.form.oilVolume) {
          queryTruckOilInByOilVolume({ tractorId: this.currentSelectCar.tractorId, oilVolume: this.form.oilVolume }).then(rsp => {
            this.oilDetail = {
              totalAmount: rsp.data.totalAmount,
              purchaseList: rsp.data.oilInList
            }
          })
        } else {
          this.oilDetail = {
            totalAmount: '--',
            purchaseList: []
          }
        }
      }
    },
    handleCarSelect (key, option) {
      this.currentSelectCar = this.carLikeData.filter(v => v.tractorId === key)[0]
      this.form.rate = this.currentSelectCar.singleOilConsumption
      this.rateKey = 'singleOilConsumption' // 默认选中单重
      this.form.tractorId = this.currentSelectCar.tractorId // 选中牵引车
      if (this.currentSelectCar.trailerId) {
        this.form.trailerId = this.currentSelectCar.trailerId
      } else {
        this.form.trailerId = ''
      }
      this.handleCarNameChange()
      this.onChangeK2()
    },
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.confirmLoading = true
          addTruckOilInAndOutByOut(this.form).then(rsp => {
            this.$message.success('创建成功')
            this.$emit('close', true)
            setTimeout(() => { this.confirmLoading = false }, 1000)
          }).catch(() => { this.confirmLoading = false })
        }
      })
    },
    handleCancel () {
      this.$emit('close')
    }
  },
  watch: {
    visible () {
      if (this.visible) {
        this.handleCarNameChange()
        this.queryDriverDown()
        this.queryTruckNumberDown()
        Object.assign(this, initData())
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
